import { getToken } from '@/utils/storage';

const initialState = {
  profile: {} as ProfileType,
  auth: getToken(),
  user: {} as UserInfo,
};

export type AuthType = {
  token: string;
  refresh_token: string;
};

export type UserInfo = {
  id: string;
  name: string;
  photo: string;
  art_count: number;
  follow_count: number;
  fans_count: number;
  like_count: number;
};
export type ProfileType = {
  id: string;
  photo: string;
  name: string;
  mobile: string;
  gender: number;
  birthday: string;
  intro: string;
};

type UserAtion =
  | { type: 'user/saveAuth'; payload: AuthType }
  | { type: 'user/saveUserInfo'; payload: UserInfo }
  | { type: 'user/saveProfile'; payload: ProfileType }
  | { type: 'user/updateProfile'; payload: Partial<ProfileType> };

export default function userReducer(state = initialState, action: UserAtion): typeof initialState {
  switch (action.type) {
    case 'user/saveAuth':
      return {
        ...state,
        auth: action.payload,
      };

    case 'user/saveUserInfo':
      return {
        ...state,
        user: { ...action.payload },
      };
    case 'user/saveProfile':
      return {
        ...state,
        profile: { ...action.payload },
      };
    case 'user/updateProfile':
      return {
        ...state,
        profile: {
          ...state.profile,
          ...action.payload,
        },
      };
    default:
      return state;
  }
}
